import { Button, Form } from 'antd';
import BasicConfig from './components/BasicConfig';
import KeyValueList from './components/KeyValueList';
import type { FormHttpConfig, HttpConfig } from './types/http';
import BodyConfig from './components/BodyConfig';

const mock: HttpConfig = {
  host: 'http://127.0.0.1:4523/m1/6920757-6636810-default',
  api: '/api/chat',
  method: 'GET',
  params: { a: '1', 'b-2': '2' },
  headers: { 'access-token': 'abc', 'Content-Type': 'application/json' },
  body: { array: [1, 2, 3], bool: true, color: 'gold', num: 123 },
};

const normalize = (values: FormHttpConfig): HttpConfig => ({
  ...values,
  params: Object.fromEntries(values.params || []),
  headers: Object.fromEntries(values.headers || []),
  // body: JSON.parse(values.body || '{}'),
});

const HttpConfigForm: React.FC = () => {
  const [form] = Form.useForm<FormHttpConfig>();

  const onFinish = (values: FormHttpConfig) => {
    console.log('提交', normalize(values));
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={{
        ...mock,
        params: Object.entries(mock.params),
        headers: Object.entries(mock.headers),
        body: JSON.stringify(mock.body, null, 2),
      }}
    >
      <BasicConfig />
      <KeyValueList name="params" title="Params" />
      <KeyValueList name="headers" title="Headers" />
      <BodyConfig />
      <Form.Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default HttpConfigForm;
